
function FlickrPhotoset(jsonPhotosetOrId, ajaxManager)
{
	var that_ = this; // required for private function support

	// fixme: perhaps save whole jsonPhotoset (retrieve if only id was passed in)
	var photosetId_ = typeof(jsonPhotosetOrId) == "object" ? jsonPhotosetOrId.id : jsonPhotosetOrId;
	var ajaxManager_ = ajaxManager;

	var photos_ = new Array();
	var currentPhotoIndex_ = -1;


	this.callbackPrevPhoto = function(callback)
	{
		var prevPhotoIndex = currentPhotoIndex_ - 1;
		if (prevPhotoIndex < 0)
			return;

		currentPhotoIndex_ = prevPhotoIndex;
		callback(that_.getCurrentPhoto());
	}


	this.getCurrentPhoto = function()
	{
		if (currentPhotoIndex_ < 0 || currentPhotoIndex_ >= photos_.length)
			return null;
 
		var jsonPhoto = photos_[currentPhotoIndex_];
		if (jsonPhoto.flickrPhoto == null)
			jsonPhoto.flickrPhoto = new FlickrPhoto(jsonPhoto, ajaxManager);
		return jsonPhoto.flickrPhoto;
	}


	var nextPhotoCallback_ = null;
	this.callbackNextPhoto = function(callback)
	{
		if (nextPhotoCallback_ != null)
			return; // can only have one callback waiting on this at one time

		if (!processNextPhotoCallback_(callback)) {
			nextPhotoCallback_ = callback;
			if (!retrieveNextPhotosPage_())
				nextPhotoCallback_ = null;
		}
	}


	// fixme: this is getting very messy.  maybe try iterators?
	function processNextPhotoCallback_(callback)
	{
		var nextPhotoIndex = currentPhotoIndex_ + 1;
		if (nextPhotoIndex < 0 || nextPhotoIndex >= photos_.length)
			return false;

		currentPhotoIndex_ = nextPhotoIndex;
		callback(that_.getCurrentPhoto());
		return true;
	}


	function retrieveNextPhotosPage_()
	{
		if (photos_.length % 10 != 0)
			return false; // no more photos because last page didn't retrieve a full 10

		var lastPage = photos_.length / 10;
		var pageToRetrieve = lastPage + 1;

		var params = {
			"photoset_id": photosetId_,
			"per_page": "10",
			"page": pageToRetrieve,
			"extras": "tags,url_s,url_m"
		};
		ajaxManager_.get("flickr.photosets.getPhotos", params, getNextPhotosPageCallback_());
		return true;
	}


	function getNextPhotosPageCallback_()
	{
		var flickrPhotoset = that_;
		return function(response)
			{ flickrPhotoset.processNextPhotosPage(response); }
	}


	this.processNextPhotosPage = function(response)
	{
		if (response != null && response.photoset.photo.length > 0) {
			photos_ = photos_.concat(response.photoset.photo);
			onPhotosAdded_();
		}
	}


	function onPhotosAdded_()
	{
		if (nextPhotoCallback_ != null)
			processNextPhotoCallback_(nextPhotoCallback_);
		nextPhotoCallback_ = null;
	}
}

